﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Xugege.AbpExtension.Application.Extension.BaseInfo.Dto;
using Abp.Extensions;
using Abp.Organizations;
using Abp.UI;
using Mono.CSharp;
using Xugege.AbpExtension.Authorization.Users;
using Xugege.AbpExtension.Core.Extension.BaseInfo;

namespace Xugege.AbpExtension.Application.Extension.BaseInfo
{
    public class TelInfoAppService : AbpZeroTemplateAppServiceBase, ITelInfoAppService
    {
        private readonly IRepository<BaseTelInfo, long> _baseTelInfo;
        private readonly IRepository<User, long> _userService;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitService;
        public TelInfoAppService(IRepository<BaseTelInfo, long> baseTelInfo,
            IRepository<User, long> userService,
            IRepository<OrganizationUnit, long> organizationUnitService)
        {
            _baseTelInfo = baseTelInfo;
            _userService = userService;
            _organizationUnitService = organizationUnitService;
        }
        /// <summary>
        /// 根据电话查找相关信息（包含电话对应的用户，组织单位）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<TelInfoOutputDto> GetUserTelInfo(TelInfoInputDto input)
        {
            if (input.Tel.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("ParamError"));
            }
            var telinfo = await _baseTelInfo.GetAll().FirstOrDefaultAsync(m => m.Tel.Trim() == input.Tel.Trim());
            if (telinfo != null)
            {

                var output = telinfo.MapTo<TelInfoOutputDto>();
                await SetTelinfoModel(output);
                return output;
            }
            return null;
        }

        /// <summary>
        /// 添加新的电话信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<long> Add(TelInfoInputDto input)
        {
            if (input.Tel.IsNullOrEmpty())
            {
                throw new UserFriendlyException("必须录入电话");
            }
            if (input.UserId.HasValue)
            {
                var user = await _userService.GetAsync(input.UserId.Value);
                if (user == null)
                {
                    throw new UserFriendlyException("关联的用户在系统中不存在");
                }
            }
            if (input.OrganizationUnitId.HasValue)
            {
                var org = await _organizationUnitService.GetAsync(input.OrganizationUnitId.Value);
                if (org == null)
                {
                    throw new UserFriendlyException("关联的部门在系统中不存在");
                }
            }
            try
            {
                var model = input.MapTo<BaseTelInfo>();
                model.Id = 0;
                model.TenantId = (await GetCurrentTenantAsync()).Id;
                return await _baseTelInfo.InsertAndGetIdAsync(model);
            }
            catch (Exception e)
            {
                throw new UserFriendlyException(L("CheckInput"));
            }

        }

        public async Task Update(TelInfoInputDto input)
        {
            if (!input.Id.HasValue)
            {
                throw new UserFriendlyException(L("CheckInput"));
            }
            var telInfo = await _baseTelInfo.GetAsync(input.Id.Value);
            if (telInfo == null)
            {
                throw new UserFriendlyException("电话信息不存在");
            }
            if (input.UserId.HasValue)
            {
                var user = await _userService.GetAsync(input.UserId.Value);
                if (user == null)
                {
                    throw new UserFriendlyException("关联的用户在系统中不存在");
                }
                else
                    telInfo.UserId = input.UserId.Value;

            }
            if (input.OrganizationUnitId.HasValue)
            {
                var org = await _organizationUnitService.GetAsync(input.OrganizationUnitId.Value);
                if (org == null)
                {
                    throw new UserFriendlyException("关联的部门在系统中不存在");
                }
                else
                    telInfo.OrganizationUnitId = input.OrganizationUnitId.Value;
            }
            telInfo.Name = input.Name;
            await _baseTelInfo.UpdateAsync(telInfo);
        }

        private async Task SetTelinfoModel(TelInfoOutputDto output)
        {

            if (output.UserId.HasValue)
            {
                var user = await _userService.GetAsync(output.UserId.Value);
                if (user != null)
                {
                    output.UserName = user.UserName;
                }
            }
            if (output.OrganizationUnitId.HasValue)
            {
                var org = await _organizationUnitService.GetAsync(output.OrganizationUnitId.Value);
                if (org != null)
                {
                    output.OrganizationUnitName = org.DisplayName;
                }
            }
        }

        /// <summary>
        /// 获取所有电话信息
        /// </summary>
        /// <returns></returns>
        public async Task<IList<TelInfoOutputDto>> GetAll()
        {
            var result = (await _baseTelInfo.GetAllListAsync()).MapTo<IList<TelInfoOutputDto>>();
            foreach (var item in result)
            {
                await SetTelinfoModel(item);
            }
            return result;
        }

        public async Task Remove(EntityDto<long> input)
        {
            var m = await _baseTelInfo.GetAsync(input.Id);
            if (m != null)
            {
                await _baseTelInfo.DeleteAsync(m);
            }
            else
            {
                throw new UserFriendlyException("删除的对象不存在");
            }
        }
    }
}
